/*
 * Copyright (C) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <aki/jsbind.h>
#include "aki/asyncworker/asyncworker.h"

napi_value ReturnPromiseNumber(int number)
{
    auto num = new int;
    if (num == nullptr) {
        return nullptr;
    }
    *num = number;
    aki::AsyncWorker worker;
    worker.SetData(num);
    napi_async_execute_callback exe = [](napi_env env, void *data) {
        auto asyncData = (aki::AsyncWorker::AsyncData *)(data);
        auto num = reinterpret_cast<int*>(asyncData->data);
        *num = *num + 1;
    };
    worker.SetExecuteCallback(exe);

    napi_async_complete_callback clt = [](napi_env env, napi_status status, void *data) {
        napi_handle_scope scope;
        napi_open_handle_scope(env, &scope);
        auto asyncData = (aki::AsyncWorker::AsyncData *)(data);
        auto num = reinterpret_cast<int*>(asyncData->data);
        napi_value result;
        napi_create_int32(env, *num, &result);
        napi_resolve_deferred(env, asyncData->deferred_, result);
        delete num;
        napi_close_handle_scope(env, scope);
    };
    
    worker.SetCompleteCallback(clt);
    napi_value promise = worker.CreateAsyncWorker();
    worker.Queue();
    
    return promise;
}

JSBIND_GLOBAL()
{
    JSBIND_FUNCTION(ReturnPromiseNumber);
}
